<template>
  <q-page padding>
    <div class="q-pa-md">
      <q-table
        title="部门管理"
        :rows="rows"
        :columns="columns"
        row-key="id"
        :filter="filter"
        flat
        bordered
        :grid="$q.screen.lt.md"
      >
        <template v-slot:top>
          <q-btn color="primary" label="新增部门" @click="openAddDialog" />
          <q-space />
          <q-input borderless dense debounce="300" v-model="filter" placeholder="搜索">
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
        </template>

        <template v-slot:item="props">
          <div class="q-pa-xs col-xs-12 col-sm-6 col-md-4">
            <q-card flat bordered>
              <q-card-section class="text-center">
                <strong>{{ props.row.name }}</strong>
              </q-card-section>
              <q-separator />
              <q-card-section>
                <div class="flex justify-between">
                  <span>父级部门:</span>
                  <span>{{ getDepartmentNameById(props.row.parent_id, rows) }}</span>
                </div>
                <div class="flex justify-between">
                  <span>状态:</span>
                  <q-badge :color="props.row.status === '正常' ? 'positive' : 'negative'">
                    {{ props.row.status }}
                  </q-badge>
                </div>
              </q-card-section>
              <q-card-actions align="right">
                <q-btn dense round flat icon="edit" @click="openEditDialog(props.row)"></q-btn>
                <q-btn dense round flat icon="delete" @click="confirmDelete(props.row)"></q-btn>
              </q-card-actions>
            </q-card>
          </div>
        </template>

        <template v-slot:body-cell-status="props">
          <q-td :props="props">
            <q-badge :color="props.row.status === '正常' ? 'positive' : 'negative'">
              {{ props.row.status }}
            </q-badge>
          </q-td>
        </template>

        <template v-slot:body-cell-actions="props">
          <q-td :props="props">
            <q-btn dense round flat icon="edit" @click="openEditDialog(props.row)"></q-btn>
            <q-btn dense round flat icon="delete" @click="confirmDelete(props.row)"></q-btn>
          </q-td>
        </template>
      </q-table>
    </div>

    <!-- Add/Edit Dialog -->
    <q-dialog v-model="dialogVisible" persistent>
      <q-card style="min-width: 350px">
        <q-card-section>
          <div class="text-h6">{{ isEditMode ? '编辑部门' : '新增部门' }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-input dense v-model="formData.name" label="部门名称" autofocus />
          <q-select
            dense
            v-model="formData.parent_id"
            :options="parentDepartmentOptions"
            label="父级部门"
            emit-value
            map-options
            clearable
          />
          <q-select dense v-model="formData.status" :options="['正常', '禁用']" label="部门状态" />
        </q-card-section>

        <q-card-actions align="right" class="text-primary">
          <q-btn flat label="取消" v-close-popup />
          <q-btn flat :label="isEditMode ? '保存' : '新增'" @click="saveItem" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { computed } from 'vue';
import { useQuasar } from 'quasar';
import { useCrud } from '../composables/useCrud';
import mockDepartments from '../assets/mock-departments.json';

const $q = useQuasar();

// 1. Define page-specific configuration and helpers
const getDepartmentNameById = (id, allRows) => {
  if (id === null) return '无';
  const department = allRows.find(d => d.id === id);
  return department ? department.name : '未知';
};

const columns = [
  { name: 'id', label: '部门ID', align: 'left', field: 'id', sortable: true },
  { name: 'name', label: '部门名称', align: 'left', field: 'name', sortable: true },
  {
    name: 'parent_id',
    label: '父级部门',
    align: 'left',
    field: 'parent_id',
    // We pass the rows from the composable to the format function
    format: (val, row) => getDepartmentNameById(val, rows.value),
    sortable: true
  },
  { name: 'status', label: '状态', align: 'center', field: 'status', sortable: true },
  {
    name: 'create_time',
    label: '创建时间',
    align: 'left',
    field: 'create_time',
    sortable: true,
    format: (val) => new Date(val).toLocaleString(),
  },
  { name: 'actions', label: '操作', align: 'center' },
];

const departmentFactory = () => ({
  name: '',
  parent_id: null,
  status: '正常',
  create_time: '' // For auto-populating creation date
});

// 2. Use the composable
const {
  rows,
  filter,
  dialogVisible,
  isEditMode,
  formData,
  openAddDialog,
  openEditDialog,
  saveItem,
  confirmDelete,
} = useCrud({
  initialRows: mockDepartments,
  itemFactory: departmentFactory,
  itemName: '部门',
  beforeDelete: (item, allRows) => {
    const hasChildren = allRows.some(d => d.parent_id === item.id);
    if (hasChildren) {
      $q.dialog({
        title: '无法删除',
        message: `部门 “${item.name}” 含有子部门，请先删除或移动子部门。`,
        ok: '知道了'
      });
      return false; // Prevent deletion
    }
    return true; // Allow deletion
  }
});

// 3. Define page-specific computed properties
const parentDepartmentOptions = computed(() => {
  const availableDepts = isEditMode.value ? rows.value.filter(d => d.id !== formData.value.id) : rows.value;
  const options = availableDepts.map(d => ({ label: d.name, value: d.id }));
  options.unshift({ label: '无 (设为顶级部门)', value: null });
  return options;
});

</script>